package com.qcc.cashier.react.module;

import com.facebook.react.bridge.Promise;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.bridge.ReadableMap;
import com.facebook.react.bridge.WritableMap;
import com.facebook.react.modules.core.RCTNativeAppEventEmitter;
import com.google.gson.Gson;
import com.landicorp.android.eptapi.DeviceService;
import com.landicorp.android.eptapi.exception.ReloginException;
import com.landicorp.android.eptapi.exception.RequestException;
import com.landicorp.android.eptapi.exception.ServiceOccupiedException;
import com.landicorp.android.eptapi.exception.UnsupportMultiProcess;
import com.qcc.cashier.pos.PosHelper;
import com.qcc.cashier.react.ReactUtils;
import com.qcc.cashier.utils.ArgumentsUtils;
import com.qcc.cashier.utils.FileUtils;
import com.qcc.cashier.utils.ImageUtils;

import java.util.HashMap;
import java.util.Map;

import javax.annotation.Nonnull;

import io.reactivex.Observable;

public class PosModule extends ReactContextBaseJavaModule {

	private ReactApplicationContext reactContext;

	public PosModule(@Nonnull ReactApplicationContext reactContext) {
		super(reactContext);
		this.reactContext = reactContext;
	}

	@Nonnull
	@Override
	public String getName() {
		return "PosModule";
	}

	@ReactMethod
	public void setId(String id, Promise promise) {
		PosHelper.setId(id);
		promise.resolve(true);
	}

	@ReactMethod
	public void setAppKey(String appKey, Promise promise) {
		PosHelper.setAppKey(appKey);
		promise.resolve(true);
	}

	@ReactMethod
	public void pay(double amount, String extOrderNo, Promise promise) {
		Observable<String> observable = PosHelper.pay(getCurrentActivity(), amount, extOrderNo);
		ReactUtils.subscribe(observable, promise);
	}

	@ReactMethod
	public void payHj(boolean posT,double amount, String extOrderNo, String name, String accountNo,String merchantNo, Promise promise) {
		Observable<String> observable = PosHelper.payHj(getCurrentActivity(),posT, amount, extOrderNo,name,accountNo,merchantNo);
		ReactUtils.subscribe(observable, promise);
	}

	@ReactMethod
	public void payHjTest(boolean posT,String payJson, Promise promise) {
		Observable<String> observable = PosHelper.payHjTest(getCurrentActivity(),posT, payJson);
		ReactUtils.subscribe(observable, promise);
	}

	@ReactMethod
	public void payQRCode(double amount, String extOrderNo, Promise promise) {
		Observable<String> observable = PosHelper.payQRCode(getCurrentActivity(), amount, extOrderNo);
		ReactUtils.subscribe(observable, promise);
	}

	@ReactMethod
	public void cancelOrder(String orgTraceNo, Promise promise) {
		Observable<String> observable = PosHelper.cancelOrder(getCurrentActivity(), orgTraceNo);
		ReactUtils.subscribe(observable, promise);
	}

	@ReactMethod
	public void cancelOrderHj(boolean posT,String orgTraceNo, Promise promise) {
		Observable<String> observable = PosHelper.cancelOrderHj(getCurrentActivity(), posT,orgTraceNo);
		ReactUtils.subscribe(observable, promise);
	}

	@ReactMethod
	public void rePrint(String orgTraceNo, Promise promise) {
		Observable<String> observable = PosHelper.rePrint(getCurrentActivity(), orgTraceNo);
		ReactUtils.subscribe(observable, promise);
	}

	@ReactMethod
	public void balance( Promise promise) {
		Observable<String> observable = PosHelper.balance(getCurrentActivity());
		ReactUtils.subscribe(observable, promise);
	}

	@ReactMethod
	public void sign( Promise promise) {
		Observable<String> observable = PosHelper.sign(getCurrentActivity());
		ReactUtils.subscribe(observable, promise);
	}

	@ReactMethod
	public void balanceYe( Promise promise) {
		Observable<String> observable = PosHelper.balanceYe(getCurrentActivity());
		ReactUtils.subscribe(observable, promise);
	}

	@ReactMethod
	public void callTrans( Promise promise,String transAppName,String transAppId,String transDataJson) {
		Observable<String> observable = PosHelper.callTrans(getCurrentActivity(),transAppName,transAppId,transDataJson);
		ReactUtils.subscribe(observable, promise);
	}

	@ReactMethod
	public void setupCardReader(ReadableMap map, Promise promise) {
		PosHelper.setupCardReader(getCurrentActivity(), map.getString("loginAddress"), map.getString("md5Key"))
				.subscribe(result -> {
					promise.resolve(result);
				}, err -> {
					promise.reject(err);
				});
	}

	@ReactMethod
	public void readCardInfo(Promise promise) {
		PosHelper.readCardInfo(getCurrentActivity()).subscribe(result -> {
			if (result.isStart()) {
				reactContext.getJSModule(RCTNativeAppEventEmitter.class).emit("readBegin", result.getResMsg());
			} else if (result.isComplete()) {
				promise.resolve(ReactUtils.toReactData(result.getBean()));
			} else if (result.isError()) {
				reactContext.getJSModule(RCTNativeAppEventEmitter.class).emit("readFail", result.getResMsg());
			}
		}, err -> promise.reject(err));
	}

	@ReactMethod
	public void stopReadCard(Promise promise) {
		try {
		PosHelper.stopReadCard();
		DeviceService.logout();
		promise.resolve(true);
		} catch (Exception e) {
			e.printStackTrace();
			promise.reject(e);
		}
	}

	@ReactMethod
	public void getPosInfo(Promise promise) {
		String posInfo = PosHelper.getPosInfo(getCurrentActivity());
		WritableMap writableMap = ArgumentsUtils.toWritableMap(new Gson().fromJson(posInfo, Map.class));
		promise.resolve(writableMap);
	}

	@ReactMethod
	public void print(String base64Image, Promise promise) {
		try{
			String temp = ImageUtils.saveTo(ImageUtils.getBitmapBase64(base64Image), "temp");
			String resultStr = PosHelper.posPrint(getCurrentActivity(), temp);
			FileUtils.deleteFile(temp);
			HashMap<String, String> hashMap = new Gson().fromJson(resultStr, HashMap.class);
			if (hashMap != null && hashMap.containsKey("resultCode") && "0".equals(hashMap.get("resultCode"))) {
				promise.resolve(true);
			} else if (hashMap != null && hashMap.containsKey("resultMsg")) {
				promise.reject(new Throwable(hashMap.get("resultMsg")));
			} else {
				promise.reject(new Throwable("打印失败" + resultStr));
			}
		}catch (Error er){
			promise.reject(new Throwable("打印失败" + er));
		}


	}

	@ReactMethod
	public void printText(String text, Promise promise) {
		try{
		String resultStr = PosHelper.posPrintText(text);
		promise.reject(new Throwable(resultStr));
		}catch (Error er) {
			promise.reject(new Throwable("打印失败" + er));
		}
	}

	@ReactMethod
	public void settings( int settingType,Promise promise) {
		PosHelper.settings(getCurrentActivity(),settingType);
		promise.resolve(true);
	}

	@ReactMethod
	public void autoSelfUpdate(Promise promise) {
		Observable<String> observable = PosHelper.autoSelfUpdate(getCurrentActivity());
		ReactUtils.subscribe(observable, promise);
	}

	@ReactMethod
	public void queryOrder(String extOrderNo,Promise promise){
		HashMap map = new HashMap();
		map.put("extOrderNo",extOrderNo);
		Observable<String> observable =PosHelper.callTrans(getCurrentActivity(),"公共资源","交易明细",new Gson().toJson(map));
		ReactUtils.subscribe(observable, promise);
	}

}
